const Router = require('koa-router')
const router = new Router()

var fs = require("fs");

function doReadFile_old(filename) {
    return new Promise((resolve, reject) => {
        fs.readFile(filename, 'utf-8', function (err, data) {
            if (err) {
                reject(err)
            }
            else {
                //console.log("异步读取: " + data)
                resolve(data)
            }
        });
    })
}

//以下是学习的精炼的写法
function doReadFile(filename) {
    return new Promise((resolve, reject) => {
        fs.readFile(filename, 'utf-8', (err, data) => {
            err ? reject(err) : resolve(data)
        }
        )
    })
}

//test.txt 
router.get('/readFileAsync', async (ctx, next) => {
    let data = await doReadFile("./public/data/" + 'vit.json')
    console.log("异步读取: data = ", data)
    //这是 Express 的时候的设置
// res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});//设置response编码为utf-8
//怎么都不行？

    //ctx.response.header= {'Content-Type':'text/html;charset=utf-8'} // 'text/html;charset=utf-8' // 'text/plain' //'html'
    ctx.type = 'html'
    ctx.body =
        {
            status: 'success',
            filename: "./public/data/" + 'test.txt',
            fileData: data //JSON.stringify(data)
        }
}
)

module.exports = router;
